/***************************************************************************

Russian to Myanmar Dictionary Google Talk Bot
Bot Coder - Sun Thurein Aung
Dictionary Source - http://www.ru-mm.org
Version - 1.0 Beta
Last Updated - 4.01.2009
GTalk connection code from 
http://jlindberg.blogspot.com/2007/12/simple-echo-bot-in-java-google-talk-now.html
http://wsdlj2ee.blogspot.com/2005/09/writing-xmpp-chat-client-in-java.html

***************************************************************************/



import java.io.*;
import java.util.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.Roster.SubscriptionMode;

public class GTalkDict{
	
	String username;
	String password;
	String dictFile;
    String dictversion, botversion;
	Hashtable dictionary;
    String[] commands = new String[]{"/help" , "/dictversion", "/botversion", "/total"};

	
	XMPPConnection conn;
	
	GTalkDict(String configFile) {
		readConfigFile(configFile);	
		loadDictionary();
		startConnection();
	}
	
	void startConnection() {
		try {
			ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
			conn = new XMPPConnection(config);
		
			conn.connect();
			conn.login(username, password);
            Presence presenc = new Presence(Presence.Type.available);
            presenc.setStatus("Bot is ready to translate. Type /help for help menu");
			// Become available.
			conn.sendPacket(presenc);
			// Auto-accept all friend requests.   
			conn.getRoster().setSubscriptionMode(SubscriptionMode.accept_all);
		}
		catch(XMPPException e) {
			e.printStackTrace();
		}


		final MessageListener messageListener = new MessageListener() {
			public void processMessage(Chat chat, Message message) {
				
				if ((message.getType() == Message.Type.chat
				|| message.getType() == Message.Type.normal)
		         && message.getBody()!= null) {
					try {
                        String text = message.getBody().toLowerCase();	// change the incoming text to lower case characters
						Date date = new Date();		// get current date and time
						DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm ");
						System.out.println( dateFormat.format(date) +  message.getFrom() + " ==> " + message.getBody());  // log the words
                        if (isCommand(text))
                        {
                            doCommand(text, chat);  // if the text is command word, do the command function
                        } // end of isCommand if
                        else if (dictionary.containsKey(text)) // if the dictionary has the meaning of the given text
                        {
                                chat.sendMessage((String)dictionary.get(text));
                        }
                        else
                        {
                            chat.sendMessage("Sorry, your word is not in dictionary.");
                        } // end of else
					} catch(XMPPException e) {
						e.printStackTrace();
					}
				}
		     }
		   };
		   
		  conn.getChatManager().addChatListener(
		       new ChatManagerListener() {
		         public void chatCreated(Chat chat, boolean createdLocally) {
		           chat.addMessageListener(messageListener);
		         }
		     }
		    );
		}


	public void readConfigFile(String configFile) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(configFile));
            System.out.println(configFile);
			username = br.readLine();
			password = br.readLine();
			dictFile = br.readLine();
            botversion = br.readLine();
			br.close();
			System.out.println(username);
			System.out.println(password);
			System.out.println(dictFile);
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}	
		
	public void loadDictionary() {
		String srcLine, dstLine;
		dictionary = new Hashtable();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(dictFile), "UTF-8"));
            dictversion = br.readLine();
			srcLine = br.readLine();
			dstLine = br.readLine();
			while(srcLine != null && dstLine != null) {
                if (!dictionary.containsKey(srcLine))
                {dictionary.put(srcLine, dstLine);}
                srcLine = br.readLine();
				dstLine = br.readLine();
			}
            br.close();
            System.out.println("done");
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}

    boolean isCommand(String text) // check the given text is command word or not
    {
        for (int i=0; i <commands.length; i++)
        {
            if (commands[i].equals(text))
                return true; // given text is command
        }
        return false; // given text is not command
    }// end of isCommand function

    void doCommand(String command, Chat chat)
    {
        String message="";
        if (commands[0].equals(command)) // if command is /help
        {
            message = "To translate a russian word, simply type a word and press Enter. Bot will give you the meaning of word in burmese.\nYou need to have Zawgyi font to see in burmese.\n/help - display this menu\n/dictversion - current version of the dictionary\n/botverion - current version of the bot\n/total - total words in dictionary";

        }// end of if /help

        if (commands[1].equals(command)) // if command is /dictversion
        {
            message = dictversion;

        }// end of if /dictversion
        
        if (commands[2].equals(command)) // if command is /botversion
        {
            message = botversion;

        }// end of if /botversion

        if (commands[3].equals(command)) // if command is /total
        {
            message = "Total words in the dictionary - " + dictionary.size();

        }// end of if /total
        try{
            chat.sendMessage(message);
        } catch(XMPPException e) {
			e.printStackTrace();
		}
    }// end of doCommand function
	
	public static void main(String args[]) {
		GTalkDict bot = new GTalkDict("config.txt");
		System.out.println("Bot is running... ");
		while(true);
	}

}
